package com.koushikdutta.ion.bitmap;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.koushikdutta.async.util.StreamUtility;
import com.koushikdutta.ion.Ion;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class IonBitmapCache {
    static final /* synthetic */ boolean $assertionsDisabled = (!IonBitmapCache.class.desiredAssertionStatus());
    LruBitmapCache cache;
    long errorCacheDuration = 30000;
    double heapRatio = 0.14285714285714285d;
    Ion ion;
    DisplayMetrics metrics;
    Resources resources;

    public IonBitmapCache(Ion ion) {
        Context context = ion.getContext();
        this.ion = ion;
        this.metrics = new DisplayMetrics();
        ((WindowManager) context.getSystemService("window")).getDefaultDisplay().getMetrics(this.metrics);
        this.resources = new Resources(context.getAssets(), this.metrics, context.getResources().getConfiguration());
        this.cache = new LruBitmapCache(getHeapSize(context) / 7);
    }

    public void put(BitmapInfo info) {
        if ($assertionsDisabled || Thread.currentThread() == Looper.getMainLooper().getThread()) {
            int maxSize = (int) (((double) getHeapSize(this.ion.getContext())) * this.heapRatio);
            if (((long) maxSize) != this.cache.maxSize()) {
                this.cache.setMaxSize((long) maxSize);
            }
            this.cache.put(info.key, info);
            return;
        }
        throw new AssertionError();
    }

    public BitmapInfo get(String key) {
        if (key == null) {
            return null;
        }
        BitmapInfo ret = this.cache.getBitmapInfo(key);
        if (ret == null || ret.bitmaps != null || ret.loadTime + this.errorCacheDuration > System.currentTimeMillis()) {
            return ret;
        }
        this.cache.remove(key);
        return null;
    }

    private Point computeTarget(int minx, int miny) {
        int targetWidth = minx;
        int targetHeight = miny;
        if (targetWidth == 0) {
            targetWidth = this.metrics.widthPixels;
        }
        if (targetWidth <= 0) {
            targetWidth = Integer.MAX_VALUE;
        }
        if (targetHeight == 0) {
            targetHeight = this.metrics.heightPixels;
        }
        if (targetHeight <= 0) {
            targetHeight = Integer.MAX_VALUE;
        }
        return new Point(targetWidth, targetHeight);
    }

    private Options prepareBitmapOptions(Options o, int minx, int miny) throws BitmapDecodeException {
        if (o.outWidth < 0 || o.outHeight < 0) {
            throw new BitmapDecodeException(o.outWidth, o.outHeight);
        }
        Point target = computeTarget(minx, miny);
        int scale = Math.max(o.outWidth / target.x, o.outHeight / target.y);
        Options ret = new Options();
        ret.inSampleSize = scale;
        ret.outWidth = o.outWidth;
        ret.outHeight = o.outHeight;
        ret.outMimeType = o.outMimeType;
        return ret;
    }

    public Options prepareBitmapOptions(File file, int minx, int miny) throws BitmapDecodeException {
        Options o = new Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.toString(), o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public Options prepareBitmapOptions(byte[] bytes, int offset, int length, int minx, int miny) throws BitmapDecodeException {
        Options o = new Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(bytes, offset, length, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public Options prepareBitmapOptions(Resources res, int id, int minx, int miny) throws BitmapDecodeException {
        Options o = new Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, id, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    public Options prepareBitmapOptions(InputStream in, int minx, int miny) throws BitmapDecodeException {
        Options o = new Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(in, null, o);
        return prepareBitmapOptions(o, minx, miny);
    }

    private static Bitmap getRotatedBitmap(Bitmap bitmap, int rotation) {
        if (bitmap == null) {
            return null;
        }
        if (rotation == 0) {
            return bitmap;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate((float) rotation);
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public static Bitmap loadBitmap(byte[] bytes, int offset, int length, Options o) {
        if ($assertionsDisabled || Thread.currentThread() != Looper.getMainLooper().getThread()) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, offset, length, o);
            if (bitmap == null) {
                return null;
            }
            return getRotatedBitmap(bitmap, Exif.getOrientation(bytes, offset, length));
        }
        throw new AssertionError();
    }

    @TargetApi(10)
    public static Bitmap loadRegion(BitmapRegionDecoder decoder, Rect sourceRect, int inSampleSize) {
        Options options = new Options();
        options.inSampleSize = inSampleSize;
        return decoder.decodeRegion(sourceRect, options);
    }

    public static Bitmap loadBitmap(Resources res, int id, Options o) {
        if ($assertionsDisabled || Thread.currentThread() != Looper.getMainLooper().getThread()) {
            int rotation;
            InputStream inputStream = null;
            try {
                inputStream = res.openRawResource(id);
                byte[] bytes = new byte[50000];
                rotation = Exif.getOrientation(bytes, 0, inputStream.read(bytes));
            } catch (Exception e) {
                rotation = 0;
            }
            StreamUtility.closeQuietly(inputStream);
            return getRotatedBitmap(BitmapFactory.decodeResource(res, id, o), rotation);
        }
        throw new AssertionError();
    }

    public static Bitmap loadBitmap(InputStream stream, Options o) throws IOException {
        if ($assertionsDisabled || Thread.currentThread() != Looper.getMainLooper().getThread()) {
            int rotation;
            MarkableInputStream in = new MarkableInputStream(stream);
            in.mark(50000);
            try {
                byte[] bytes = new byte[50000];
                rotation = Exif.getOrientation(bytes, 0, in.read(bytes));
            } catch (Exception e) {
                rotation = 0;
            }
            in.reset();
            return getRotatedBitmap(BitmapFactory.decodeStream(in, null, o), rotation);
        }
        throw new AssertionError();
    }

    public static Bitmap loadBitmap(File file, Options o) {
        if ($assertionsDisabled || Thread.currentThread() != Looper.getMainLooper().getThread()) {
            int rotation;
            FileInputStream fin = null;
            try {
                FileInputStream fin2 = new FileInputStream(file);
                try {
                    byte[] bytes = new byte[50000];
                    rotation = Exif.getOrientation(bytes, 0, fin2.read(bytes));
                    fin = fin2;
                } catch (Exception e) {
                    fin = fin2;
                    rotation = 0;
                    StreamUtility.closeQuietly(fin);
                    return getRotatedBitmap(BitmapFactory.decodeFile(file.toString(), o), rotation);
                }
            } catch (Exception e2) {
                rotation = 0;
                StreamUtility.closeQuietly(fin);
                return getRotatedBitmap(BitmapFactory.decodeFile(file.toString(), o), rotation);
            }
            StreamUtility.closeQuietly(fin);
            return getRotatedBitmap(BitmapFactory.decodeFile(file.toString(), o), rotation);
        }
        throw new AssertionError();
    }

    private static int getHeapSize(Context context) {
        return (((ActivityManager) context.getSystemService("activity")).getMemoryClass() * 1024) * 1024;
    }
}
